package com.zzy.backend.service.impl.user.account;

import com.zzy.backend.mapper.UserMapper;
import com.zzy.backend.pojo.User;
import com.zzy.backend.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author molimark<br />
 * @date: 2023/1/30 14:36<br/>
 * @description: <br/>
 */

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private UserMapper userMapper;

    //这里自动装配的是SecurityConfig中的Bean
    /*
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    **/
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Map<String, String> register(String username, String password, String confirmPassword) {
        Map<String,String> map = new HashMap<>();
        if(username == null){
            map.put("error_message","用户名不能为空");
            return map;
        }
        if(password == null || confirmPassword == null){
            map.put("error_message","密码不能为空");
            return map;
        }

        username = username.trim();
        System.out.println(username);
        System.out.println(password);
        System.out.println(confirmPassword);
        if(username.length() == 0){
            map.put("error_message","用户名不能为空");
            return map;
        }

        if(password.length() == 0 || confirmPassword.length() == 0){
            map.put("error_message","密码不能为空");
            return map;
        }
        System.out.println("1");
        if(username.length() > 100){
            map.put("error_message","用户名长度不能大于100");
            return map;
        }

        if(password.length() > 100 || confirmPassword.length() > 100){
            map.put("error_message","密码长度不能大于100");
            return map;
        }
        
        System.out.println("2");
        if(!password.equals(confirmPassword)){
            map.put("error_message","两次输入的密码不一致");
            return map;
        }
        System.out.println("3");
        User queryUser = userMapper.searchUserByUsername(username);
        if(queryUser!=null){
            map.put("error_message","用户名已存在");
            return map;
        }

        String encodedPassword = passwordEncoder.encode(password);
        String photo = "https://cdn.acwing.com/media/user/profile/photo/152078_lg_fee4c00974.jpg";

        User user = new User(null,username,encodedPassword,photo);
        userMapper.addUser(user);
        map.put("error_message","success");
        return map;
    }
}
